import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getOnlineDevices, refreshDevices as apiRefreshDevices, registerDevice } from '@/api/device'
import { generateDeviceId, getDeviceName, generateDeviceName } from '@/utils/deviceUtils'
import { ElMessage } from 'element-plus'

export const useDeviceStore = defineStore('device', () => {
  // 当前设备信息
  const currentDevice = ref({
    id: '',
    deviceName: '',
    ipAddress: '',
    status: 1 // 在线
  });
  
  // 设备列表
  const deviceList = ref([]);
  
  // 状态
  const loading = ref(false)
  
  // 注册当前设备到服务器
  const registerCurrentDevice = async () => {
    if (!currentDevice.value.id || !currentDevice.value.deviceName) return
    
    try {
      await registerDevice({
        id: currentDevice.value.id,
        deviceName: currentDevice.value.deviceName,
        ipAddress: '', // IP地址由服务端获取
        status: 1 // 在线状态
      })
      console.log('设备注册成功')
    } catch (error) {
      console.error('设备注册失败', error)
      // 注册失败不影响本地使用
    }
  }
  
  // 初始化设备
  const initDevice = () => {
    // 从本地存储中获取设备ID
    const storedDeviceId = localStorage.getItem('deviceId');
    const storedDeviceName = localStorage.getItem('deviceName');
    
    if (storedDeviceId) {
      currentDevice.value.id = storedDeviceId;
      currentDevice.value.deviceName = storedDeviceName || generateDeviceName();
    } else {
      // 生成新的设备ID和名称
      currentDevice.value.id = generateDeviceId();
      currentDevice.value.deviceName = generateDeviceName();
      
      // 保存到本地存储
      localStorage.setItem('deviceId', currentDevice.value.id);
      localStorage.setItem('deviceName', currentDevice.value.deviceName);
    }
    
    // 尝试注册设备到服务器
    registerCurrentDevice()
  };
  
  // 更新设备信息
  const updateDevice = (deviceInfo) => {
    if (deviceInfo.deviceName) {
      currentDevice.value.deviceName = deviceInfo.deviceName;
      localStorage.setItem('deviceName', deviceInfo.deviceName);
    }
    
    if (deviceInfo.ipAddress) {
      currentDevice.value.ipAddress = deviceInfo.ipAddress;
    }
    
    if (deviceInfo.status !== undefined) {
      currentDevice.value.status = deviceInfo.status;
    }
  };
  
  // 更新设备名称
  const updateDeviceName = (newName) => {
    currentDevice.value.deviceName = newName;
    localStorage.setItem('deviceName', newName);
  };
  
  // 更新设备列表
  const setDeviceList = (devices) => {
    deviceList.value = devices;
  };
  
  // 添加设备到列表
  const addDevice = (device) => {
    const index = deviceList.value.findIndex(d => d.id === device.id);
    if (index === -1) {
      deviceList.value.push(device);
    } else {
      deviceList.value[index] = device;
    }
  };
  
  // 移除设备
  const removeDevice = (deviceId) => {
    const index = deviceList.value.findIndex(d => d.id === deviceId);
    if (index !== -1) {
      deviceList.value.splice(index, 1);
    }
  };
  
  // 在线设备数量
  const onlineDeviceCount = computed(() => {
    return deviceList.value.filter(device => device.status === 1).length;
  });
  
  // 当前设备ID
  const currentDeviceId = computed(() => currentDevice.value.id);

  // 当前设备名称
  const deviceName = computed(() => currentDevice.value.deviceName);
  
  // 获取在线设备列表
  const loadDevices = async () => {
    loading.value = true
    try {
      const res = await getOnlineDevices()
      if (res && res.data) {
        // 过滤掉自己的设备
        deviceList.value = res.data.filter(device => device.id !== currentDevice.value.id)
      }
    } catch (error) {
      console.error('获取设备列表失败', error)
      ElMessage.error('获取设备列表失败')
    } finally {
      loading.value = false
    }
  }
  
  // 刷新设备列表
  const refreshDevices = async () => {
    loading.value = true
    try {
      // 发送设备发现请求
      await apiRefreshDevices()
      
      // 多次轮询获取最新设备列表
      const pollCount = 3
      const pollInterval = 1000
      
      for (let i = 0; i < pollCount; i++) {
        await new Promise(resolve => setTimeout(resolve, pollInterval))
        await loadDevices()
      }
      
      ElMessage.success('设备列表刷新成功')
    } catch (error) {
      ElMessage.error('刷新设备列表失败')
      console.error('刷新设备列表失败', error)
    } finally {
      loading.value = false
    }
  }
  
  return { 
    currentDevice, 
    deviceList, 
    onlineDeviceCount,
    currentDeviceId,
    deviceName,
    initDevice,
    updateDevice,
    updateDeviceName,
    setDeviceList,
    addDevice,
    removeDevice,
    loading,
    loadDevices,
    refreshDevices
  };
}) 